package com.yootk.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yootk.dbc.DatabaseConnection;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/city.action") // 城市的加载
public class CityServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        long pid = Long.parseLong(req.getParameter("pid")); // 接收省份数据
        String sql = "SELECT cid,title FROM city WHERE pid=?"; // 获取全部省份信息
        JSONArray array = new JSONArray();
        try {
            PreparedStatement pstmt = DatabaseConnection.getConnection().prepareStatement(sql);
            pstmt.setLong(1, pid); // 设置省份编号
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                JSONObject city = new JSONObject();
                city.put("cid", rs.getLong(1));
                city.put("title", rs.getString(2));
                array.add(city); // 添加JSONObject项
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseConnection.close();
        }
        resp.getWriter().print(array.toJSONString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
